/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.persistence.dao;

import com.edu.kamai.persistence.beans.Contest;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author xyzhu
 */
public class ContestDao {
    private static final Log log = LogFactory.getLog(Contest.class);
    public static final String CONTEST_BEAN = "com.edu.kamai.persistence.beans.Contest";
    private Session session = null;
    
    public ContestDao(){
        this.session  = kamaiHibernateUtil.getSessionFactory().openSession();
    }
    
    public void addContest(Contest contest){
        log.debug("save contest instance");
        
        try{
            Transaction tx = session.beginTransaction();
            session.save(contest);
            tx.commit();
            log.debug("save successful");
        }catch(RuntimeException re){
            log.error("update failed",re);
            throw re;
        }
    }
    
    public void delContest(Contest contest){
        try{
            Transaction tx = session.beginTransaction();
            session.delete(contest);
            tx.commit();
            log.debug("delete successful");
        }catch(RuntimeException re){
            log.error("delete failed",re);
            throw re;
        }
    }
    
    public List<Contest> findContest(){
        try{
            Transaction tx = session.beginTransaction();
            String hqlStr=new String("from Contest");
            List<Contest> contests = session.createQuery(hqlStr).list();
            tx.commit();
            log.debug("find contest successful");
            return contests;
        }catch(RuntimeException re){
            log.error("find contest failed",re);
            return null;
        }
    }
    
    public Contest findContestByID(int cid){
        try{
            //Transaction tx = session.beginTransaction();
            //String hqlStr=new String("from Contest where contest_id=" + id);
            Contest contest = (Contest)session.get(CONTEST_BEAN, cid);
            return contest;
            
        }catch(RuntimeException re){
            log.error("find contest by id failed",re);
            return null;
        }
    }
    
}
